package com.hbsoft.util;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;

import com.hb.util.DateUtil;

public final class EncryptUtil {
	private final static SimpleDateFormat FORMAT = DateUtil.DATE_YMDHMS_THREE_FORMAT;

	private final static String[] KEYS = new String[] { "82e45fa366dcbb4c413b017158f4898e",
			"0b8ccc1ff4b6ced32d7eb32ef1aaff6e", "54309b73eafae49d312a05ba32000ac9", "c0dc4f2094561a79c817056793ada13c",
			"c3a54a89d577c8162a63e15b17e9f5c9", "53cbd45c2121f2393080ef18bbfc7562", "6b21f3e017b2e895d1c2fc01ad297431",
			"89601f8886e6d999c1fead3558e50b27", "de9ead5880fdf3beb9af4fbfbb5b8ff8", "fc025784fb0282bdefaf76f8712abb30",
			"964dd57732714f35b6ec1c09ceb23758", "536154b4fb24936b50a63c549657b789" };

	private final static String _sign(String data) {
		String result = "";

		try {
			if (data != null && data.length() > 0) {
				int n = 0;
				if (data.length() > 10) {
					n = data.charAt(2);
					n = n % 10;
				}
				data = n + data + KEYS[n];
				result = DigestUtils.sha1Hex(data.getBytes("UTF-8"));
			}
		} catch (UnsupportedEncodingException e) {
		}

		return result;
	}

	public static String pass(String src, int start, int end, String key) {
		int cur, i;
		char[] a = src.toCharArray();
		char[] b = key.toCharArray();

		int srcLen = b.length;
		for (i = start; i < end && i < a.length; i++) {
			cur = (i - start) % srcLen;
			a[i] ^= b[cur];
		}
		return new String(a);
	}

	public final static String sign(Object... obj) {
		StringBuilder result = new StringBuilder();

		result.append('~');
		for (Object o : obj) {
			if (o == null) {
				result.append("NULL");
			} else if (o instanceof Date) {
				result.append(FORMAT.format((Date) o));
			} else {
				result.append(String.valueOf(o));
			}
			result.append('~');
		}

		return _sign(result.toString());
	}

	public final static boolean verifySign(String signString, Object... obj) {
		boolean result = false;

		String sign = sign(obj);

		if (sign != null && sign.length() > 0 && sign.equals(signString)) {
			result = true;
		}

		return result;
	}
	
	public static void main(String[] args) {
		System.out.println(sign("608047","42113.60","40913.60"));
	}

}
